"use client";

import React, { useState, useEffect } from "react";
import { Settings, Moon, Sun, Server } from "lucide-react";
import { useTheme } from "./ui/theme";
import axios from "axios";

interface HeaderProps {
  onOpenSettings: () => void;
}

export function Header({ onOpenSettings }: HeaderProps) {
  const { theme, setTheme } = useTheme();
  const [connectionStatus, setConnectionStatus] = useState<'loading' | 'connected' | 'disconnected'>('loading');
  
  useEffect(() => {
    // 检查与Ollama API的连接状态
    const checkConnection = async () => {
      try {
        setConnectionStatus('loading');
        
        // 获取设置信息
        const settingsResponse = await axios.get("/api/settings");
        const apiEndpoint = settingsResponse.data.apiEndpoint;
        
        if (!apiEndpoint) {
          setConnectionStatus('disconnected');
          return;
        }
        
        // 构建测试请求URL
        const url = new URL(apiEndpoint);
        // 获取基础URL
        const baseUrl = `${url.protocol}//${url.host}`;
        const testUrl = `${baseUrl}/api/tags`;
        
        // 测试连接
        await axios.get(testUrl, { timeout: 3000 });
        setConnectionStatus('connected');
      } catch (error) {
        console.error("API连接检查失败:", error);
        setConnectionStatus('disconnected');
      }
    };
    
    // 页面加载时检查连接
    checkConnection();
    
    // 设置定期检查
    const interval = setInterval(checkConnection, 60000); // 每分钟检查一次
    
    return () => {
      clearInterval(interval);
    };
  }, []);
  
  const toggleTheme = () => {
    setTheme(theme === "dark" ? "light" : "dark");
  };
  
  return (
    <header className="border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 sticky top-0 z-10">
      <div className="container max-w-4xl mx-auto flex items-center justify-between h-16 px-4">
        <div className="flex items-center space-x-2">
          <h1 className="text-xl font-semibold text-slate-900 dark:text-slate-100">
            DeepSeek Chat
          </h1>
          
          <div className={`ml-3 flex items-center px-2 py-1 rounded-full text-xs font-medium ${
            connectionStatus === 'connected' 
              ? 'bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-400' 
              : connectionStatus === 'loading'
                ? 'bg-yellow-50 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400 animate-pulse'
                : 'bg-red-50 text-red-700 dark:bg-red-900/30 dark:text-red-400'
          }`}>
            <Server className="h-3 w-3 mr-1" />
            <span>
              {connectionStatus === 'connected' 
                ? 'Ollama 已连接' 
                : connectionStatus === 'loading' 
                  ? '检查连接中...' 
                  : 'Ollama 未连接'}
            </span>
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <button
            type="button"
            onClick={toggleTheme}
            className="p-2 rounded-md text-slate-600 hover:text-slate-900 hover:bg-slate-100 dark:text-slate-400 dark:hover:text-slate-100 dark:hover:bg-slate-800 transition-colors"
            title={theme === "dark" ? "切换到浅色模式" : "切换到深色模式"}
          >
            {theme === "dark" ? (
              <Sun className="h-5 w-5" />
            ) : (
              <Moon className="h-5 w-5" />
            )}
          </button>
          
          <button
            type="button"
            onClick={onOpenSettings}
            className="p-2 rounded-md text-slate-600 hover:text-slate-900 hover:bg-slate-100 dark:text-slate-400 dark:hover:text-slate-100 dark:hover:bg-slate-800 transition-colors"
            title="打开设置"
          >
            <Settings className="h-5 w-5" />
          </button>
        </div>
      </div>
    </header>
  );
} 